package org.laizili.solution.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * <a href="https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/">3. 无重复字符的最长子串</a>
 * <p>
 * tags: 滑动窗口;
 * </p>
 */
public class Problem3 {
    private static class Solution {
        public int lengthOfLongestSubstring(String s) {
            char[] charArray = s.toCharArray();
            int len = s.length();
            int left = 0, right = 0;
            int res = 0;
            Set<Character> set = new HashSet<>();
            while (right < len) {
                // 核心思想：右动左不动；左动右不动
                if (set.contains(charArray[right])) {
                    res = Math.max(right - left, res);
                    set.remove(charArray[left]);
                    left++;
                } else {
                    set.add(charArray[right]);
                    right++;
                }
            }
            // 最后更新一次结果
            return Math.max(res, right - left);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution().lengthOfLongestSubstring("tmmzuxt")); // 5
        System.out.println(new Solution().lengthOfLongestSubstring("abcabcbb")); //3
    }
}
